package com.terra.ns.imp.auth.controller

import com.aliyun.dingtalkcontact_1_0.models.GetUserHeaders
import com.aliyun.dingtalkoauth2_1_0.models.GetUserTokenRequest
import com.aliyun.teautil.models.RuntimeOptions
import com.terra.ns.imp.auth.config.UserLoginProperties
import com.terra.ns.imp.auth.constant.AuthErrorCode
import com.terra.ns.imp.auth.exception.AuthServiceException
import com.terra.ns.imp.auth.service.ILoginService
import com.terra.ns.imp.common.dingtalk.client.DingtalkClient
import io.swagger.v3.oas.annotations.tags.Tag
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam

/**
@author qins
@date 2023/8/16
@desc
 */
@Controller
@RequestMapping("/ding")
@Tag(name = "dingLogin")
class DingDingLoginController {

    private val log = LoggerFactory.getLogger(this::class.java)

    @Autowired
    private lateinit var dingtalkClient: DingtalkClient

    @Autowired
    private lateinit var loginUserService: ILoginService

    @Autowired
    private lateinit var userLoginProperties: UserLoginProperties

    @GetMapping("/auth")
    fun auth(@RequestParam(value = "authCode") authCode: String): String {
        try {
            // 根据授权码获取用户相关访问token
            val dingConf = dingtalkClient.getDingtalkConf()
            val request = GetUserTokenRequest().setCode(authCode).setGrantType("authorization_code").setClientId(dingConf.appKey).setClientSecret(dingConf.appSecret)
            val accessToken = dingtalkClient.authClient().getUserToken(request).getBody().getAccessToken()
            // 根据用户相关访问token获取用户信息
            val getUserHeaders = GetUserHeaders().setXAcsDingtalkAccessToken(accessToken)
            val me = dingtalkClient.contactClient().getUserWithOptions("me", getUserHeaders, RuntimeOptions())
            val userMobile = me.getBody().mobile
            // 进行免密登录
            val loginResult = loginUserService.passwordlessLogin(userMobile)
            return "redirect:${userLoginProperties.loginSuccessPage}?token=${loginResult.token}"
        } catch (ex: AuthServiceException) {
            log.error("用户免密登录失败", ex)
            return "redirect:${userLoginProperties.noRegisterPage}?type=notFoundUser"
        } catch (ex: Exception) {
            log.error("获取钉钉用户信息错误，钉钉授权登录失败", ex)
            throw AuthServiceException(AuthErrorCode.DINGDING_LOGIN_ERROR)
        }
    }


}